// 星座测试统计图表功能实现

// 为单个tab内容区域初始化性格分析图表
function initPersonalityChart() {
    // 获取当前激活的tab内容中的图表容器
    const personalityChartContainer = document.querySelector('#personality-content .chart-container');
    if (personalityChartContainer) {
        // 确保只初始化一次，移除已存在的canvas
        const existingCanvas = personalityChartContainer.querySelector('canvas');
        if (existingCanvas) {
            existingCanvas.remove();
        }
        
        const canvas = document.createElement('canvas');
        canvas.id = 'personalityChart';
        personalityChartContainer.appendChild(canvas);
        
        // 创建雷达图
        const ctx = canvas.getContext('2d');
        
        // 销毁可能存在的Chart实例
        if (window.personalityChartInstance) {
            window.personalityChartInstance.destroy();
        }
        
        // 星座性格特征数据
        const zodiacData = {
            labels: ['外向性', '宜人度', '尽责性', '神经质', '开放性'],
            datasets: [
                {
                    label: '白羊座',
                    data: [90, 60, 70, 65, 85],
                    backgroundColor: 'rgba(255, 99, 132, 0.2)',
                    borderColor: 'rgba(255, 99, 132, 1)',
                    pointBackgroundColor: 'rgba(255, 99, 132, 1)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgba(255, 99, 132, 1)'
                },
                {
                    label: '金牛座',
                    data: [50, 75, 85, 55, 60],
                    backgroundColor: 'rgba(54, 162, 235, 0.2)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    pointBackgroundColor: 'rgba(54, 162, 235, 1)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgba(54, 162, 235, 1)'
                },
                {
                    label: '双子座',
                    data: [85, 70, 60, 75, 90],
                    backgroundColor: 'rgba(255, 206, 86, 0.2)',
                    borderColor: 'rgba(255, 206, 86, 1)',
                    pointBackgroundColor: 'rgba(255, 206, 86, 1)',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: 'rgba(255, 206, 86, 1)'
                }
            ]
        };
        
        // 创建雷达图
        window.personalityChartInstance = new Chart(ctx, {
            type: 'radar',
            data: zodiacData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    },
                    title: {
                        display: true,
                        text: '十二星座性格特征雷达图'
                    }
                },
                scales: {
                    r: {
                        angleLines: {
                            display: true
                        },
                        suggestedMin: 0,
                        suggestedMax: 100
                    }
                }
            }
        });
    }
}

// 为单个tab内容区域初始化爱情匹配图表
function initLoveChart() {
    // 先尝试查找带ID的容器，如果找不到则查找普通的图表容器
    let loveChartContainer = document.querySelector('#love-content .chart-container');
    if (!loveChartContainer) {
        loveChartContainer = document.querySelector('.chart-container');
    }
    
    if (loveChartContainer) {
        const existingCanvas = loveChartContainer.querySelector('canvas');
        if (existingCanvas) {
            existingCanvas.remove();
        }
        
        // 确保有canvas元素
        if (!loveChartContainer.querySelector('canvas')) {
            const canvas = document.createElement('canvas');
            canvas.id = 'loveChart';
            loveChartContainer.appendChild(canvas);
        }
        
        const canvas = loveChartContainer.querySelector('canvas');
        
        // 创建爱情匹配图表
        const ctx = canvas.getContext('2d');
        
        if (window.loveChartInstance) {
            window.loveChartInstance.destroy();
        }
        
        // 爱情观统计柱状图数据
        const loveData = {
            labels: ['注重感情', '注重外貌', '注重性格', '注重经济', '注重默契'],
            datasets: [{
                label: '男性',
                data: [65, 70, 75, 60, 80],
                backgroundColor: '#5AC8FA',
                borderRadius: 8
            },
                {
                    label: '女性',
                    data: [75, 65, 85, 65, 85],
                    backgroundColor: '#FF2D55',
                    borderRadius: 8
                }]
        };
        
        window.loveChartInstance = new Chart(ctx, {
            type: 'bar',
            data: loveData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: '百分比 (%)'
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'top',
                    }
                }
            }
        });
    }
}

// 为单个tab内容区域初始化职业倾向图表
function initCareerChart() {
    const careerChartContainer = document.querySelector('#career-content .chart-container');
    if (!careerChartContainer) {
        careerChartContainer = document.querySelector('.chart-container');
    }
    
    if (careerChartContainer) {
        const existingCanvas = careerChartContainer.querySelector('canvas');
        if (existingCanvas) {
            existingCanvas.remove();
        }
        
        // 确保有canvas元素
        if (!careerChartContainer.querySelector('canvas')) {
            const canvas = document.createElement('canvas');
            canvas.id = 'careerChart';
            careerChartContainer.appendChild(canvas);
        }
        
        const canvas = careerChartContainer.querySelector('canvas');
        
        // 创建职业倾向图表
        const ctx = canvas.getContext('2d');
        
        if (window.careerChartInstance) {
            window.careerChartInstance.destroy();
        }
        
        // 职业倾向数据
        const careerData = {
            labels: ['技术类', '管理类', '创意类', '服务类', '学术类', '艺术表演类'],
            datasets: [
                {
                    label: '火象星座',
                    data: [65, 85, 75, 70, 60, 80],
                    backgroundColor: '#FF2D55',
                    borderRadius: 8
                },
                {
                    label: '土象星座',
                    data: [80, 75, 60, 75, 85, 65],
                    backgroundColor: '#34C759',
                    borderRadius: 8
                },
                {
                    label: '风象星座',
                    data: [75, 65, 85, 80, 70, 75],
                    backgroundColor: '#5AC8FA',
                    borderRadius: 8
                },
                {
                    label: '水象星座',
                    data: [60, 70, 80, 85, 75, 85],
                    backgroundColor: '#AF52DE',
                    borderRadius: 8
                }
            ]
        };
        
        window.careerChartInstance = new Chart(ctx, {
            type: 'bar',
            data: careerData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '职业领域'
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '星座元素职业倾向分布'
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                let label = context.dataset.label || '';
                                if (label) {
                                    label += ': ';
                                }
                                if (context.parsed.y !== null) {
                                    label += context.parsed.y + '%';
                                }
                                return label;
                            }
                        }
                    },
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }
}

// 兼容之前的函数名
function initCareerCharts() {
    initCareerChart();
}

// 初始化生活方式页面图表
function initLifestyleCharts() {
    // 直接获取现有的canvas元素
    const canvas = document.getElementById('lifestyleChart');
    if (canvas) {
        // 销毁可能存在的Chart实例
        if (canvas.chart) {
            canvas.chart.destroy();
        }

        // 兴趣爱好分布数据
        const lifestyleData = {
            labels: ['阅读', '音乐', '运动', '旅行', '电影', '游戏', '美食'],
            datasets: [{
                label: '喜欢程度',
                data: [65, 80, 70, 85, 75, 60, 90],
                backgroundColor: 'rgba(52, 199, 89, 0.2)',
                borderColor: '#34C759',
                borderWidth: 2,
                tension: 0.4,
                fill: true
            }]
        };

        // 创建折线图
        canvas.chart = new Chart(canvas, {
            type: 'line',
            data: lifestyleData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: '百分比 (%)'
                        }
                    }
                }
            }
        });
    }
}

// 保留原函数以保持兼容性
function initLifestyleChart() {
    initLifestyleCharts();
}

// 初始化睡眠习惯图表
function initSleepChart() {
    const sleepCanvas = document.getElementById('sleepChart');
    if (sleepCanvas) {
        // 销毁可能存在的Chart实例
        if (sleepCanvas.chart) {
            sleepCanvas.chart.destroy();
        }
        
        const sleepData = {
            labels: ['早睡组', '正常作息', '熬夜组'],
            datasets: [{
                data: [35, 40, 25],
                backgroundColor: ['rgba(52, 199, 89, 0.7)', 'rgba(147, 112, 219, 0.7)', 'rgba(255, 59, 48, 0.7)'],
                borderColor: '#FFFFFF',
                borderWidth: 2
            }]
        };
        
        sleepCanvas.chart = new Chart(sleepCanvas, {
            type: 'pie',
            data: sleepData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: true,
                        position: 'bottom',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.label + ': ' + context.raw + '%';
                            }
                        }
                    }
                }
            }
        });
    }
}

// 初始化饮食习惯图表
function initDietChart() {
    const dietCanvas = document.getElementById('dietChart');
    if (dietCanvas) {
        // 销毁可能存在的Chart实例
        if (dietCanvas.chart) {
            dietCanvas.chart.destroy();
        }
        
        const dietData = {
            labels: ['健康饮食', '均衡饮食', '随意饮食', '重口味'],
            datasets: [{
                data: [30, 45, 15, 10],
                backgroundColor: ['rgba(52, 199, 89, 0.7)', 'rgba(90, 200, 250, 0.7)', 'rgba(255, 149, 0, 0.7)', 'rgba(255, 59, 48, 0.7)'],
                borderColor: '#FFFFFF',
                borderWidth: 2
            }]
        };
        
        dietCanvas.chart = new Chart(dietCanvas, {
            type: 'doughnut',
            data: dietData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '70%',
                plugins: {
                    legend: {
                        display: true,
                        position: 'bottom',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.label + ': ' + context.raw + '%';
                            }
                        }
                    }
                }
            }
        });
    }
}

// 初始化运动习惯图表
function initExerciseChart() {
    const exerciseCanvas = document.getElementById('exerciseChart');
    if (exerciseCanvas) {
        // 销毁可能存在的Chart实例
        if (exerciseCanvas.chart) {
            exerciseCanvas.chart.destroy();
        }
        
        const exerciseData = {
            labels: ['高频运动', '定期运动', '偶尔运动', '很少运动'],
            datasets: [{
                data: [25, 35, 30, 10],
                backgroundColor: ['rgba(255, 59, 48, 0.7)', 'rgba(52, 199, 89, 0.7)', 'rgba(147, 112, 219, 0.7)', 'rgba(158, 158, 158, 0.7)'],
                borderColor: '#FFFFFF',
                borderWidth: 2
            }]
        };
        
        exerciseCanvas.chart = new Chart(exerciseCanvas, {
            type: 'pie',
            data: exerciseData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: true,
                        position: 'bottom',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.label + ': ' + context.raw + '%';
                            }
                        }
                    }
                }
            }
        });
    }
}

// 初始化消费习惯图表
function initSpendingChart() {
    const spendingCanvas = document.getElementById('spendingChart');
    if (spendingCanvas) {
        // 销毁可能存在的Chart实例
        if (spendingCanvas.chart) {
            spendingCanvas.chart.destroy();
        }
        
        const spendingData = {
            labels: ['理性消费', '冲动消费', '注重品质', '节省型'],
            datasets: [{
                data: [35, 20, 25, 20],
                backgroundColor: ['rgba(147, 112, 219, 0.7)', 'rgba(255, 149, 0, 0.7)', 'rgba(90, 200, 250, 0.7)', 'rgba(52, 199, 89, 0.7)'],
                borderColor: '#FFFFFF',
                borderWidth: 2
            }]
        };
        
        spendingCanvas.chart = new Chart(spendingCanvas, {
            type: 'doughnut',
            data: spendingData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '60%',
                plugins: {
                    legend: {
                        display: true,
                        position: 'bottom',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.label + ': ' + context.raw + '%';
                            }
                        }
                    }
                }
            }
        });
    }
}

// 初始化生活习惯统计图表
function initHabitsCharts() {
    // 睡眠习惯图表 - 环形图(上图风格)
    const sleepCanvas = document.getElementById('sleepChart');
    if (sleepCanvas) {
        // 销毁可能存在的Chart实例
        if (sleepCanvas.chart) {
            sleepCanvas.chart.destroy();
        }
        
        const sleepData = {
            labels: ['早睡组', '正常作息', '熬夜组'],
            datasets: [{
                data: [35, 40, 25],
                backgroundColor: ['rgba(52, 199, 89, 0.7)', 'rgba(147, 112, 219, 0.7)', 'rgba(255, 59, 48, 0.7)'],
                borderColor: '#FFFFFF',
                borderWidth: 2
            }]
        };

        sleepCanvas.chart = new Chart(sleepCanvas, {
            type: 'pie',
            data: sleepData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: true,
                        position: 'bottom',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.label + ': ' + context.raw + '%';
                            }
                        }
                    }
                }
            }
        });
    }

    // 饮食习惯图表 - 用户指定风格
    const dietCanvas = document.getElementById('dietChart');
    if (dietCanvas) {
        // 销毁可能存在的Chart实例
        if (dietCanvas.chart) {
            dietCanvas.chart.destroy();
        }
        
        const dietData = {
            labels: ['健康饮食', '均衡饮食', '随意饮食', '重口味'],
            datasets: [{
                data: [30, 45, 15, 10],
                backgroundColor: ['rgba(52, 199, 89, 0.7)', 'rgba(90, 200, 250, 0.7)', 'rgba(255, 149, 0, 0.7)', 'rgba(255, 59, 48, 0.7)'],
                borderColor: '#FFFFFF',
                borderWidth: 2
            }]
        };

        dietCanvas.chart = new Chart(dietCanvas, {
            type: 'doughnut',
            data: dietData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '70%',
                plugins: {
                    legend: {
                        display: true,
                        position: 'bottom',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.label + ': ' + context.raw + '%';
                            }
                        }
                    }
                }
            }
        });
    }

    // 运动习惯图表 - 用户指定风格
    const exerciseCanvas = document.getElementById('exerciseChart');
    if (exerciseCanvas) {
        // 销毁可能存在的Chart实例
        if (exerciseCanvas.chart) {
            exerciseCanvas.chart.destroy();
        }
        
        const exerciseData = {
            labels: ['高频运动', '定期运动', '偶尔运动', '很少运动'],
            datasets: [{
                data: [25, 35, 30, 10],
                backgroundColor: ['rgba(255, 59, 48, 0.7)', 'rgba(52, 199, 89, 0.7)', 'rgba(147, 112, 219, 0.7)', 'rgba(158, 158, 158, 0.7)'],
                borderColor: '#FFFFFF',
                borderWidth: 2
            }]
        };

        exerciseCanvas.chart = new Chart(exerciseCanvas, {
            type: 'pie',
            data: exerciseData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: true,
                        position: 'bottom',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.label + ': ' + context.raw + '%';
                            }
                        }
                    }
                }
            }
        });
    }

    // 消费习惯图表 - 用户指定风格
    const spendingCanvas = document.getElementById('spendingChart');
    if (spendingCanvas) {
        // 销毁可能存在的Chart实例
        if (spendingCanvas.chart) {
            spendingCanvas.chart.destroy();
        }
        
        const spendingData = {
            labels: ['理性消费', '冲动消费', '注重品质', '节省型'],
            datasets: [{
                data: [35, 20, 25, 20],
                backgroundColor: ['rgba(147, 112, 219, 0.7)', 'rgba(255, 149, 0, 0.7)', 'rgba(90, 200, 250, 0.7)', 'rgba(52, 199, 89, 0.7)'],
                borderColor: '#FFFFFF',
                borderWidth: 2
            }]
        };

        spendingCanvas.chart = new Chart(spendingCanvas, {
            type: 'doughnut',
            data: spendingData,
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '60%',
                plugins: {
                    legend: {
                        display: true,
                        position: 'bottom',
                        labels: {
                            usePointStyle: true,
                            padding: 20,
                            font: {
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.label + ': ' + context.raw + '%';
                            }
                        }
                    }
                }
            }
        });
    }
}

// 在DOM加载完成后初始化所有图表
document.addEventListener('DOMContentLoaded', function() {
    // 初始化性格分析雷达图
    initPersonalityChart();
    
    // 初始化爱情匹配图表
    initLoveChart();
    
    // 初始化职业倾向图表
    initCareerChart();
    
    // 初始化生活方式图表
    initLifestyleChart();
    
    // 初始化消费习惯图表
    initSpendingChart();
    
    // 为tab切换添加事件监听器
    const tabs = document.querySelectorAll('.tab-bar button');
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            // 移除所有tab和内容的active类
            document.querySelectorAll('.tab-bar button').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            
            // 为当前点击的tab和对应内容添加active类
            this.classList.add('active');
            // 使用data-tab属性获取对应的内容区域
            const tabId = this.dataset.tab + '-content';
            document.getElementById(tabId).classList.add('active');
            
            // 根据激活的tab重新初始化对应图表
            if (tabId === 'personality-content') {
                initPersonalityChart();
            } else if (tabId === 'love-content') {
                initLoveChart();
            } else if (tabId === 'career-content') {
                initCareerChart();
            } else if (tabId === 'lifestyle-content') {
                initLifestyleChart();
            }
        });
    });
});